package com.zrl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrl.service.MessageService;
import com.zrl.utils.ConstantPropertiesUtil;
import com.zrl.utils.HttpClientUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;


/**
 * @author: zrl
 * @date: 2022/8/17 22:53
 * @description:
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private WxMpService wxMpService;

    //接收消息
    @Override
    public String receiveMessage(Map<String, String> param) {
        String content = "";
        try {
            String msgType = param.get("MsgType");
            switch(msgType){
                case "text" :
                    String msg = param.get("Content");
                    content = this.text(param,msg).toString();
                    break;
                case "event" :
                    String event = param.get("Event");
                    String eventKey = param.get("EventKey");
                    if("subscribe".equals(event)) {//关注公众号
                        content = this.subscribe(param);
                    }else {
                        content = "success";
                    }
                    break;
                default:
                    content = "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
            content = this.text(param, param.get("Content")).toString();
        }
        return content;
    }

    //推送信息
    @Override
    public void pushMessage(Map<String, String> data) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(ConstantPropertiesUtil.OPEN_ID)//要推送的用户openid
                .templateId(ConstantPropertiesUtil.TEMPLATE_ID)//模板id
                .build();
        //3,如果是正式版发送消息，，这里需要配置你的信息
        templateMessage.addData(new WxMpTemplateData("title", "今日情报-"+data.get("week"), "#BE77FF"));
        templateMessage.addData(new WxMpTemplateData("region", data.get("city"), "#FF9933"));
        templateMessage.addData(new WxMpTemplateData("textDay", data.get("textDay"), "#000000"));
        templateMessage.addData(new WxMpTemplateData("tempMax", data.get("tempMax")+"℃", "#FF5151"));
        templateMessage.addData(new WxMpTemplateData("tempMin", data.get("tempMin")+"℃", "#3399FF"));
        templateMessage.addData(new WxMpTemplateData("wind",data.get("wind"), "#3399FF"));
        templateMessage.addData(new WxMpTemplateData("loveDays", data.get("loveDays"), "#FF79BC"));
        templateMessage.addData(new WxMpTemplateData("birthday", data.get("birthday"), "#84C1FF"));
        templateMessage.addData(new WxMpTemplateData("anniversary", data.get("anniversary"), "#CA8EFF"));
        templateMessage.addData(new WxMpTemplateData("note_ch", data.get("note_ch"), "#FF99CC"));
        String msg = null;
        try {
            msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }

    //获取天气信息
    public void getWeather(Map<String,String> data){

        try {
            String location = data.get("location");
            String url = "https://devapi.qweather.com/v7/weather/3d?key="+ConstantPropertiesUtil.WEATHER_KEY+"&location="+location;
            HttpClientUtils httpClient = new HttpClientUtils(url);

            httpClient.get();
            JSONObject objectData = JSONObject.parseObject(httpClient.getContent());
            JSONArray dailyArray = objectData.getJSONArray("daily");
            JSONObject todayData = dailyArray.getJSONObject(0);
            data.put("tempMax",todayData.get("tempMax").toString());
            data.put("tempMin",todayData.get("tempMin").toString());
            data.put("textDay",todayData.get("textDay").toString());
            data.put("wind",todayData.get("windScaleDay").toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取天气内容失败");
        }
    }

    //获取城市位置信息
    @Override
    public void getCity(Map<String,String> data) {
        try {
            String location = data.get("location");
            String url = "https://geoapi.qweather.com/v2/city/lookup?key="+ConstantPropertiesUtil.WEATHER_KEY+"&location="+location;
            HttpClientUtils httpClient = new HttpClientUtils(url);

            httpClient.get();
            JSONObject objectData = JSONObject.parseObject(httpClient.getContent());
            JSONArray dailyArray = objectData.getJSONArray("location");
            JSONObject todayData = dailyArray.getJSONObject(0);
            data.put("city",todayData.get("name").toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取城市信息失败");
        }
    }

    //获取所有日期
    @Override
    public void getdate(Map<String, String> data) {
        //获取今天星期几
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
        String week = sdf.format(new Date());
        data.put("week",week);

        //获取恋爱天数
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = new Date();
        try {
            Date loveDate = sdf1.parse(ConstantPropertiesUtil.LOVE_DAY);
            //恋爱天数
            Long loveDays = (nowDate.getTime() - loveDate.getTime())/ (24*3600*1000);
            data.put("loveDays",loveDays.toString());

            //纪念日倒计时天数
            Calendar today = Calendar.getInstance();
            Calendar memoryDay = Calendar.getInstance();
            //设置时间
            today.setTime(nowDate);
            memoryDay.setTime(loveDate);
            memoryDay.set(Calendar.YEAR,today.get(Calendar.YEAR));//将纪念日就改为本年日期

            Integer days = 0;
            if (memoryDay.get(Calendar.DAY_OF_YEAR)<today.get(Calendar.DAY_OF_YEAR)){
                //纪念日已过，算明年纪念日距今多少天
                days = today.getActualMaximum(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR);
                memoryDay.set(Calendar.YEAR, today.get(Calendar.YEAR)+1); // 修改为明年的纪念日日期
                days += memoryDay.get(Calendar.DAY_OF_YEAR);
            }else{
                days = memoryDay.get(Calendar.DAY_OF_YEAR)-today.get(Calendar.DAY_OF_YEAR);
            }
            data.put("anniversary",days.toString());


            //生日倒计时天数
            Date birthday = sdf1.parse(ConstantPropertiesUtil.BIRTHDAY);
            Calendar CBirthday = Calendar.getInstance();
            CBirthday.setTime(birthday);
            CBirthday.set(Calendar.YEAR,today.get(Calendar.YEAR));//将生日改为本年日期

            if (CBirthday.get(Calendar.DAY_OF_YEAR)<today.get(Calendar.DAY_OF_YEAR)){
                //纪念日已过，算明年纪念日距今多少天
                days = today.getActualMaximum(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR);
                CBirthday.set(Calendar.YEAR, today.get(Calendar.YEAR)+1); // 修改为明年的生日日期
                days += CBirthday.get(Calendar.DAY_OF_YEAR);
            }else{
                days = CBirthday.get(Calendar.DAY_OF_YEAR)-today.get(Calendar.DAY_OF_YEAR);
            }
            data.put("birthday",days.toString());


        } catch (Exception e) {
            e.printStackTrace();
        }



    }
    //获取每日一语
    @Override
    public void getcontent(Map<String, String> data) {
        try {
            String url = "https://saying.api.azwcl.com/saying/get";
            HttpClientUtils httpClient = new HttpClientUtils(url);

            httpClient.get();
            JSONObject objectData = JSONObject.parseObject(httpClient.getContent());
            JSONObject res = objectData.getJSONObject("data");
            Object content = res.get("content");
            System.out.println(content);
            data.put("note_ch",content.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除data中的数据
    @Override
    public void cleaerMapData(Map<String, String> data) {
        if (!data.isEmpty()){
            data.clear();
        }
    }

    //处理关注事件
    private String subscribe(Map<String, String> param) {
        return this.text(param, "以后我来守护你的每一天呀").toString();
    }

    /*//处理取消关注事件
    private String unsubscribe(Map<String, String> param) {
        return "不要啊~~";
    }*/

    //回复文本
    private StringBuffer text(Map<String, String> param, String content) {
        String fromusername = param.get("FromUserName");
        String tousername = param.get("ToUserName");
        //单位为秒，不是毫秒
        Long createTime = new Date().getTime() / 1000;
        StringBuffer text = new StringBuffer();
        text.append("<xml>");
        text.append("<ToUserName><![CDATA["+fromusername+"]]></ToUserName>");
        text.append("<FromUserName><![CDATA["+tousername+"]]></FromUserName>");
        text.append("<CreateTime><![CDATA["+createTime+"]]></CreateTime>");
        text.append("<MsgType><![CDATA[text]]></MsgType>");
        text.append("<Content><![CDATA["+content+"]]></Content>");
        text.append("</xml>");
        return text;
    }
}
